package org.theSeed.base.utils;

import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import org.theSeed.base.exp.BuzExp;
import org.theSeed.base.exp.ServiceExp;
import org.theSeed.base.pojo.dto.CommonKeyValue;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 对称密钥工具
 *
 * 常用的加密算法为RSA，签名校验算法为DSA
 * 公钥用于 加密 或 验证签名
 * 私钥用于 解密 或 生成签名
 */
public class RsaUtil {
    /**
     * 生成密钥
     * @param algorithm
     * @return
     * @throws NoSuchAlgorithmException
     */
    @SneakyThrows
    public static CommonKeyValue<PublicKey,PrivateKey> createKeyPair(String algorithm, int size) {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        keyPairGenerator.initialize(size);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        return new CommonKeyValue(publicKey,privateKey);
    }

    /**
     * 生成密钥字符
     * @param algorithm
     * @return
     * @throws NoSuchAlgorithmException
     */
    @SneakyThrows
    public static CommonKeyValue<String,String> createKeyPairStr(String algorithm,int size) {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        keyPairGenerator.initialize(size);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        return new CommonKeyValue(Base64.encodeBase64String(publicKey.getEncoded()),Base64.encodeBase64String(privateKey.getEncoded()));
    }

    /**
     * 获取公钥
     * @param algorithm
     * @param publicKeyStr
     * @return
     */
    @SneakyThrows
    public static PublicKey getPublicKey(String algorithm, String publicKeyStr){
        byte[] publicKeyBytes = Base64.decodeBase64(publicKeyStr);
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
//      公钥使用规则x509
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
        return keyFactory.generatePublic(x509EncodedKeySpec);
    }

    /**
     * 获取私钥
     * @param algorithm
     * @param privateKeyStr
     * @return
     */
    @SneakyThrows
    public static PrivateKey getPrivateKey(String algorithm, String privateKeyStr){
        byte[] privateKeyBytes = Base64.decodeBase64(privateKeyStr);
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
//       私钥使用规则  PKCS8EncodedKeySpec
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        return keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    }

    /**
     * 获取密钥对
     * @param algorithm
     * @param publicKeyStr
     * @param privateKeyStr
     * @return
     */
    public static CommonKeyValue<PublicKey,PrivateKey> getKeyPair(String algorithm, String publicKeyStr, String privateKeyStr){
        PublicKey publicKey = getPublicKey(algorithm, publicKeyStr);
        PrivateKey privateKey = getPrivateKey(algorithm, privateKeyStr);
        return new CommonKeyValue(publicKey,privateKey);
    }








    /**
     * 公钥加密数据
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    @SneakyThrows
    public static String publicEncrypt(String algorithm, PublicKey publicKey, byte[] data) {
        Cipher cipher = Cipher.getInstance(algorithm);
        try {
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64String(cipher.doFinal(data));
        } catch (InvalidKeyException e) {
            throw new ServiceExp("秘钥失效");
        } catch (IllegalBlockSizeException e) {
            throw new ServiceExp("加密无效数量异常");
        } catch (BadPaddingException e) {
            throw new ServiceExp("加密错误添加异常");
        }
    }

    /**
     * 私钥解密
     * @param algorithm
     * @param privateKey
     * @param encryptedData
     * @return
     */
    @SneakyThrows
    public static String decryptWithPrivateKey(String algorithm, PrivateKey privateKey, byte[] encryptedData) {
        Cipher cipher = Cipher.getInstance(algorithm);
        try {
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return Base64.encodeBase64String(cipher.doFinal(encryptedData));
        } catch (InvalidKeyException e) {
            throw new ServiceExp("无效秘钥");
        } catch (IllegalBlockSizeException e) {
            throw new ServiceExp("秘钥错误");
        } catch (BadPaddingException e) {
            throw new ServiceExp("加密信息错误");
        }
    }

    /**
     * 私钥加密签名
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String signWithPrivateKey(String algorithm,String data, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance(algorithm);
        signature.initSign(privateKey);
        signature.update(Base64.decodeBase64(data));
        signature.sign();
        return Base64.encodeBase64String(signature.sign());
    }

    /**
     * 公钥验签
     * @param data
     * @param signatureBytes
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static boolean verifyWithPublicKey(String algorithm,String data, byte[] signatureBytes, PublicKey publicKey) throws Exception {
        Signature signature = Signature.getInstance(algorithm);
        signature.initVerify(publicKey);
        signature.update(Base64.decodeBase64(data));
        return signature.verify(signatureBytes);
    }
}
